package com.yuandengta.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

/**
 * @Author:Hardy
 * @QQ:2937270766
 * @官网：http://www.yuandengta.com
 */
public class SocketServer {
    private static class SocketTask implements Runnable {
        private Socket socket;

        public SocketTask(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            BufferedReader in = null;
            PrintWriter out = null;

            try {

                in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
                out = new PrintWriter(this.socket.getOutputStream(), true);

                String body = null;

                while ((body = in.readLine()) != null && body.length() != 0) {
                    System.out.println("the server receive msg :" + body);
                    out.println(new Date().toString());
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {

                if (in != null) {
                    try {
                        in.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if (out != null) {
                    try {
                        out.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if (this.socket != null) {
                    try {
                        this.socket.close();

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }
        }

        public static void main(String[] args) throws Exception {
            int port = 6666;
            // 监听指定的端口
            ServerSocket server = new ServerSocket(port);
            // server将一直等待连接的到来
            while (true) {
                new Thread(new SocketTask(server.accept())).start();
            }
        }
    }
}